﻿using MediatR;
using Sgr.Domain.Uow;
using Sgr.UPMS.Application.Services;
using Sgr.UPMS.Events;

namespace Sgr.UPMS.Application.DomainEventHandlers
{
    public class DepartmentChangedDomainEventHandle : INotificationHandler<DepartmentChangedDomainEvent>
    {
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IOrgBasicDataCacheService _orgBasicDataCacheService;

        public DepartmentChangedDomainEventHandle(
             IUnitOfWorkManager unitOfWorkManager,
             IOrgBasicDataCacheService orgBasicDataCacheService)
        {
            _orgBasicDataCacheService = orgBasicDataCacheService;
            _unitOfWorkManager = unitOfWorkManager;
        }

        public async Task Handle(DepartmentChangedDomainEvent notification, CancellationToken cancellationToken)
        {
            async Task clearCacheAsync()
            {
                await _orgBasicDataCacheService.RemoveDepartmentCacheAsync(notification.OrgId);
            }

            if (_unitOfWorkManager.Current != null && !_unitOfWorkManager.Current.IsCompleted)
                _unitOfWorkManager.Current.AddCompletedHandler(clearCacheAsync);
            else
                await clearCacheAsync();
        }
    }
}